package com.abu.edums.controller;


import com.abu.edums.client.VodClient;
import com.abu.pojo.Video;
import com.abu.edums.service.VideoService;
import com.abu.utils.Resp;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author 阿布
 * @since 2020-06-18
 */
@RestController
@RequestMapping("/eduservice/video")
public class VideoController {

    @Autowired
    private VideoService videoService;

    @Autowired
    private VodClient vodClient;

    /**
     * 添加小节
     *
     * @param video
     * @return
     */
    @PostMapping("addVideo")
    public Resp addVideo(@RequestBody Video video) {
        boolean flag = this.videoService.save(video);
        if (flag) {
            return Resp.ok();
        }
        return Resp.error();
    }

    @Transactional
    @DeleteMapping("{id}")
    public Resp deleteVideo(@PathVariable("id") String id) {
//        1.根据videoId查询出videoSourceId
        Video video = this.videoService.getById(id);
        String videoSourceId = video.getVideoSourceId();
//        3.同时也要删除对应的视频
        if (StringUtils.isNotBlank(videoSourceId)) {
            this.vodClient.removeAlyVideo(videoSourceId);
        }
//        2.删除数据库中的数据
        boolean flag = this.videoService.removeById(id);
        if (flag) {
            return Resp.ok();
        }
        return Resp.error();
    }

    @GetMapping("byvideoid/{videoId}")
    public Resp getVideoByChapterIdAndVideoId(@PathVariable("videoId") String videoId) {
        Video video = this.videoService.getOne(new QueryWrapper<Video>().eq("id", videoId));
            if (video != null) {
            return Resp.ok().data("video", video);
        }
        return Resp.error();
    }

    @PostMapping("updateVideo")
    public Resp updateVideoByVid(@RequestBody Video video) {
        boolean flag = this.videoService.updateById(video);
        if (flag) {
            return Resp.ok();
        }
        return Resp.error();
    }

}

